// 详情提取器 - 处理 savePolicy 和 resultMapping
import { visibilityEngine } from './visibility-engine.js'

/**
 * 处理slider类型答案的区间映射
 * @param {string} answer - 滑块值
 * @param {Object} map - 区间映射对象
 * @returns {string|null} 映射结果
 */
const handleSliderRangeMapping = (answer, map) => {
    const value = Number(answer);
    if (isNaN(value)) return null;

    for (const range in map) {
        if (range.includes('-')) {
            const [min, max] = range.split('-').map(Number);
            if (value >= min && value <= max) {
                return map[range];
            }
        } else {
            const exactValue = Number(range);
            if (value === exactValue) {
                return map[range];
            }
        }
    }
    return null;
};

/**
 * 处理问卷结果，获取针对题目的 details
 * @param {Array} answers - 答案数组
 * @param {Array} questions - 题目数组
 * @returns {Object} details
 */
export const extractResultDetailsFromAnswers = (answers, questions) => {
    if (!questions || !answers) return {};

    const details = {};

    // 构建题目对象用于可见性判断
    const questionsObj = {};
    questions.forEach((q, index) => {
        if (q && q.id) {
            questionsObj[q.id] = q;
        }
    });

    for (let i = 0; i < questions.length; i++) {
        const q = questions[i];
        if (!q) continue;

        const ans = answers[i];
        const savePolicy = q.savePolicy || "never";

        // 判断题目是否可见
        const isVisible = !q.visibleWhen || visibilityEngine.getValidQuestionIds(
            [q.id],
            ["visible"],
            answers,
            questionsObj
        ).includes(q.id);

        // 处理 details（用于发送给后端的详情）
        if (q.saveAsDetail && savePolicy !== "never") {
            let shouldSaveResult = false;
            switch (savePolicy) {
                case "always":
                    shouldSaveResult = true;
                    break;
                case "whenAnswered":
                    shouldSaveResult = ans != null && ans !== "";
                    break;
                default:
                    shouldSaveResult = false;
            }

            if (shouldSaveResult) {
                let value;
                if (q.type === 'slider') {
                    // 处理slider类型的区间映射
                    value = handleSliderRangeMapping(ans, q.saveAsDetail.map);
                } else {
                    // 其他类型使用直接映射
                    value = q.saveAsDetail.map[ans];
                }

                if (q.saveAsDetail.factId != null && value != null) {
                    details[q.saveAsDetail.factId] = value;
                }
            }
        }
    }

    return details;
}